package com.example.sicnuaccountingapp.ui.home

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.sicnuaccountingapp.data.entity.Transaction
import com.example.sicnuaccountingapp.data.entity.TransactionType
import com.example.sicnuaccountingapp.data.repository.TransactionRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import java.time.LocalDateTime
import java.time.ZoneId
import javax.inject.Inject

@HiltViewModel
class HomeViewModel @Inject constructor(
    private val transactionRepository: TransactionRepository
) : ViewModel() {

    private val _state = MutableStateFlow<HomeUiState>(HomeUiState.Loading)
    val state: StateFlow<HomeUiState> = _state.asStateFlow()

    private var currentUserId: Long = -1L

    fun setUserId(userId: Long) {
        currentUserId = userId
        loadTransactions()
    }

    private fun loadTransactions() {
        viewModelScope.launch {
            try {
                _state.value = HomeUiState.Loading
                transactionRepository.getAllTransactions(currentUserId)
                    .collect { transactions ->
                        val summary = TransactionSummary(
                            totalIncome = transactions
                                .filter { it.type == TransactionType.INCOME }
                                .sumOf { it.amount },
                            totalExpense = transactions
                                .filter { it.type == TransactionType.EXPENSE }
                                .sumOf { it.amount }
                        )

                        val groupedTransactions = transactions
                            .sortedByDescending { it.date }
                            .groupBy { formatTransactionDate(it.date) }

                        _state.value = HomeUiState.Success(
                            summary = summary,
                            transactions = groupedTransactions
                        )
                    }
            } catch (e: Exception) {
                _state.value = HomeUiState.Error(e.message ?: "加载失败")
            }
        }
    }

    private fun formatTransactionDate(timestamp: Long): String {
        val date = LocalDateTime.ofInstant(
            java.time.Instant.ofEpochMilli(timestamp),
            ZoneId.systemDefault()
        ).toLocalDate()
        
        val today = java.time.LocalDate.now()
        return when {
            date == today -> "今天"
            date == today.minusDays(1) -> "昨天"
            date.isAfter(today.minusDays(7)) -> "本周"
            date.isAfter(today.withDayOfMonth(1)) -> "本月"
            else -> "更早"
        }
    }
} 